﻿# -*- coding:utf-8 -*-
from tkinter.messagebox import *
from tkinter import *
from student_info_sql import *
from teacher_info_sql import *
from student_achievement_sql import *
from tkinter import ttk
from LoginPage import *  # 菜单栏对应的各个子页面
import xlwt

import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import numpy as np

global numbers


class StudentPage(object):
    def __init__(self, number, master=None):
        global numbers
        numbers = number
        self.root = master  # 定义内部变量root
        self.root.geometry('%dx%d' % (650, 400))  # 设置窗口大小
        self.root.resizable(0, 0)  # 防止用户调整尺寸
        self.createPage()

    def createPage(self):
        self.menuPage = MenuFrame(self.root)  # 创建不同Frame
        #   self.menuPage.pack() #默认显示界面 


class MenuFrame(Frame):  # 继承Frame类
    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.root = master  # 定义内部变量root
        self.createPage()

    def createPage(self):
        global numbers
        strs = "欢迎您！学号为：%s 的同学！" % numbers
        Label(self.root, text=strs).place(x=210, y=0)
        Button(self.root, text='查看个人成绩单', command=self.print_ach, width=20, height=10).place(x=150, y=95)
        Button(self.root, text='修改个人密码', command=self.change_pw, width=20, height=10).place(x=350, y=95)
        Button(self.root, text='导出个人成绩单为Excel表格', command=self.ach_dao_xls, width=25).place(x=230, y=295)
        Button(self.root, text='查看个人成绩折线图', command=self.show_ach_img, width=25).place(x=230, y=335)

    def show_ach_img(self):
        global numbers
        self.ach_img = Tk()
        self.ach_img.title('成绩折线图')
        winWidth = 650
        winHeight = 450
        screenWidth = self.ach_img.winfo_screenwidth()
        screenHeight = self.ach_img.winfo_screenheight()
        x = int((screenWidth - winWidth) / 2)
        y = int((screenHeight - winHeight) / 2)
        # 设置窗口初始位置在屏幕居中
        self.ach_img.geometry("%sx%s+%s+%s" % (winWidth, winHeight, x+20, y+20))

        fig = plt.figure(figsize=(10, 4), dpi=100)  # 图像比例
        f_plot = fig.add_subplot(111)  # 划分区域
        canvas_spice = FigureCanvasTkAgg(fig, self.ach_img)
        canvas_spice.get_tk_widget().pack()  # 随窗口大小调整而调整

        ach_name=achievement_lie_name()
        x_data=ach_name[2:]
        all_ach=achievement_showdb(numbers)
        y_data=[]
        for i in list(all_ach)[2:]:
            if i == None:
                y_data.append(0)
            else:
                y_data.append(int(i))
        # 画图
        plt.rcParams['font.sans-serif'] = 'SimHei'  # 全局字体
        f_plot.clear()  # 刷新
        plt.xlabel('科目', size=10)
        plt.ylabel('分数', size=10)
        plt.title('个人成绩折线图', size=10)
        plt.plot(x_data, y_data)
        for a, b in zip(x_data, y_data):
            plt.text(a, b, b, ha='center', va='bottom', fontsize=10)
        plt.grid(True)  # 网格
        canvas_spice.draw()

    def ach_dao_xls(self):
        try:
            global numbers
            a = achievement_showdb(numbers)
            a = tuple(a)
            b = achievement_lie_name()
            c = []
            c.append(tuple(b))
            c.append(a)

            def w_excel(res):
                book = xlwt.Workbook(encoding='utf-8')  # 新建一个excel
                sheet = book.add_sheet('sheet1')  # 新建一个sheet页
                for row in range(0, len(res)):
                    for col in range(0, len(res[row])):
                        sheet.write(row, col, res[row][col])
                    row += 1
                    col += 1
                book.save('%s_student_achievement.xls' % numbers)
                print("导出成功！")

            w_excel(c)
            showinfo(title='确认', message='导出成功！')
        except:
            showinfo(title='错误', message='未知错误，请重新导出！')

    def print_ach(self):
        global numbers
        self.ach = Toplevel(self.root)
        self.ach.title('个人成绩单')
        winWidth = 300
        winHeight = 200
        screenWidth = self.ach.winfo_screenwidth()
        screenHeight = self.ach.winfo_screenheight()
        x = int((screenWidth - winWidth) / 2)
        y = int((screenHeight - winHeight) / 2)
        # 设置窗口初始位置在屏幕居中
        self.ach.geometry("%sx%s+%s+%s" % (winWidth, winHeight, x, y))
        # 设置窗口图标
        # root.iconbitmap("./image/icon.ico")
        # 设置窗口宽高固定
        self.ach.resizable(0, 0)
        b = achievement_lie_name()
        a = achievement_showdb(numbers)
        a = list(a)
        if len(a) == 2:
            strs = "暂无科目成绩,请等待教师添加"
            Label(self.ach, text=strs).pack()
        else:
            for i, j in enumerate(a):
                if i >= 2:
                    strs = b[i] + ":" + str(j)
                    Label(self.ach, text=strs).pack()

    def change_pw(self):
        def sure_change():
            global numbers
            try:
                New_pw = self.new_pw.get()
                # print(User_id)
                New_pws = self.new_pws.get()
                # print(User_pw)
                if New_pw == New_pws:
                    user_alter_pw(numbers, New_pw)
                    print("学号为%s的学生已修改密码，新密码为：%s" % (numbers, New_pw))
                    showinfo(title='提示', message='密码已修改，请重启软件重新登录！')
                    self.root.destroy()
                else:
                    showinfo(title='错误', message='两次密码不一致，请重新输入！')
            except:
                showinfo(title='错误', message='未知错误，请重新输入！')

        global numbers
        self.change_pw = Toplevel(self.root)
        self.change_pw.title('修改密码')
        winWidth = 230
        winHeight = 210
        screenWidth = self.change_pw.winfo_screenwidth()
        screenHeight = self.change_pw.winfo_screenheight()
        x = int((screenWidth - winWidth) / 2)
        y = int((screenHeight - winHeight) / 2)
        # 设置窗口初始位置在屏幕居中
        self.change_pw.geometry("%sx%s+%s+%s" % (winWidth, winHeight, x, y))
        # 设置窗口图标
        # root.iconbitmap("./image/icon.ico")
        # 设置窗口宽高固定
        self.change_pw.resizable(0, 0)
        self.new_pw = StringVar()
        self.new_pws = StringVar()
        Label(self.change_pw, text='请输入新密码').place(x=110, y=0)
        Label(self.change_pw, text='新密码: ').place(x=25, y=20)
        Entry(self.change_pw, textvariable=self.new_pw, show='*').place(x=70, y=20)
        Label(self.change_pw, text='重复新密码: ').place(x=0, y=50)
        Entry(self.change_pw, textvariable=self.new_pws, show='*').place(x=70, y=50)
        Button(self.change_pw, text='确认修改', command=sure_change).place(x=90, y=90)
